import {toast, modal} from './utils.js'
import {BASE_URL} from './config.js'

// 不带token请求
const httpRequest = (url, data = '', method = 'get') => {
	// 检查网络状态
	checkNetWorkStatus();
  
  // 组装请求参数
  let httpOption = getHttpOption(url, data, method);
  
	let promise = new Promise((resolve, reject) => {
		uni.request(httpOption).then((response) => {
      let [error, res] = response;
      if(200 === res.statusCode) {
        if(200 === res.data.status) {
          resolve(res.data.data)
        } else {
          modal(res.data.message)
        }
      }
    }).catch((response) => {
      reject(response)
    }).finally(() => {
      uni.hideLoading();
    });
	})
  
	return promise
};

//带Token请求
const httpTokenRequest = (url, data = '', method = 'get') => {
	// 检查网络状态
  checkNetWorkStatus();
  
	let token = uni.getStorageSync('token');
	
	if (token == '' || token == undefined || token == null) {
		toast('登录后才可以这么做！');
		
		return false;
	} 

	// 组装请求参数
	let httpOption = getHttpOption(url, data, method, token);
	
	let promise = new Promise((resolve, reject) => {
		uni.request(httpOption).then((response) => {
			let [error, res] = response;
			if(200 === res.statusCode) {
			  if(200 === res.data.status) {
			    resolve(res.data.data);
			  } else {
			    modal(res.data.message);
			  }
			}
		}).catch((response) => {
				reject(response)
		})
	})
	
	return promise
};


// 检查网络状态
const checkNetWorkStatus = () => {
  uni.onNetworkStatusChange(function(res) {
  	if (!res.isConnected) {
      toast('网络连接不可用！');
  	}
    
  	return false
  });
};


// 组装请求参数
const getHttpOption = (url, data, method, token = '') => {
  let httpOption = {
  	url: BASE_URL + url,
  	data: data,
  	method: method,
  	header: {
      'Authorization': 'Bearer ' + token,
  		'X-Requested-With': 'XMLHttpRequest',
  		'Content-Type': 'application/json; charset=UTF-8'
  	},
  	dataType: 'json',
  }
  
  return httpOption;
};



// 拦截器
const hadToken = () => {
	let token = uni.getStorageSync('token');

	if (token == '' || token == undefined || token == null) {
		uni.showToast({
			title: '账号已过期，请重新登录',
			icon: 'none',
			complete: function() {
				uni.navigateTo({
					url: '/pages/index?index=4'
				});
			}
		});
		return false;
	}
	return true
}

export default {
	httpRequest,
	httpTokenRequest
}
